
import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:flutter_logan/flutter_logan.dart';

mixin ScreenCallback {
   void onDuration(int duration, String formatText){}
   void onStartRecording(String path, String? evidID){}
   void onTakeShotOk(int num){}
   void onStopRecord(Map map, String? evidID){}
   void onCallback(int code){}
   void sendLog(String log) {
      print("screen callback: $log");
      FlutterLogan.log("screen callback: $log");
   }
}

class FlutterScreenRecord {
  static ScreenCallback? _callback;

  static const MethodChannel _channel = MethodChannel('com.jacky/flutter_screen_recording');

  ///开始录屏
  ///
  ///[mp4Dir] 视频文件和截图文件存放目录
  ///
  ///[maxRecordSecond] 允许最大录制时长(单位：秒)
  ///
  ///[serverTime] 录制开始时间
  ///
  ///[checkSim]  是否需要检测sim卡
  ///
  ///[macState]  录制的模式： 0-静音；1-外放；2-内录
  ///
  ///[sha256]  true: 使用sha256方式获取摘要；false：使用md5方式获取摘要
  static startScreenRecord(String mp4Dir, int maxRecordSecond, int serverTime, bool checkSim, int macState, bool sha256, String evidId) {
    _channel.invokeMethod('startScreenRecord', {
      "mp4Dir": mp4Dir,
      "maxRecordSecond": maxRecordSecond,
      "serverTime": serverTime,
      "checkSim": checkSim,
      "macState": macState,
      "digest": sha256 ? "SHA-256" : '',
      "evidId": evidId
    });
  }

  ///android 进行后台
  static moveTaskToBack({bool nonRoot = true})async{
    return _channel.invokeMethod("moveTaskToBack",{"nonRoot": nonRoot});
  }

  static void stopScreenRecord() {
    _channel.invokeMethod("stopScreenRecord");
  }

  static void bindScreenRecord({ScreenCallback? callBack, bool selfScreen = true}) {
    _setCallback(callBack);
    _channel.invokeMethod("bindScreenRecord", {'self': selfScreen});
  }

  static void unbindScreenRecord() {
    _channel.invokeMethod("unbindScreenRecord");
    _channel.setMethodCallHandler(null);
    _callback = null;
  }

  static Future<bool> isScreenRecording() {
    return _channel.invokeMethod("isScreenRecording").then((value) => value??false);
  }


  ///[timeCallBack] 设置录屏时长回调通知,返回 00:00:00 格式的字符串
  ///
  ///[shotCallBack] 设置截屏数量回调通知，返回 123...数字
  ///
  ///[msgCallBack] 设置清洁性检查回调
  static void _setCallback(ScreenCallback? callBack) {
    _callback = callBack;
    _channel.setMethodCallHandler((call) async {
      String method = call.method;
      switch(method) {
        case "sendLog" :
          _callback?.sendLog(call.arguments);
          break;
        case "onDurationUI" :
          _callback?.onDuration(call.arguments['duration'], call.arguments['formatText']);
          break;
        case "onStartRecordingUI" :
          if(Platform.isIOS) {
            _callback?.onStartRecording(call.arguments, null);
          } else {
            _callback?.onStartRecording(
                call.arguments['text'], call.arguments['evidId']);
          }
          break;
        case "onTakeShotOkUI" :
          _callback?.onTakeShotOk(call.arguments);
          break;
        case "onStopRecordUI" :
          if(Platform.isIOS) {
            _callback?.onStopRecord(call.arguments, null);
          } else {
            String? back = call.arguments['text'];
            String evid = call.arguments['evidId'];
            if(back == null || back.isEmpty) {
              _callback?.onCallback(6);
            } else {
              _callback?.onStopRecord(jsonDecode(back), evid);
            }
          }
          break;
        case "onCallbackUI" :
          _callback?.onCallback(call.arguments);
          break;
      }
    });
  }


  ///Android 应用是否已经 加入白名单/是忽略电量优化的应用
  ///返回值：null代表Android sdk版本低于23，false/true
  static isIgnoreBatteryOptimizations(){
    if (!Platform.isAndroid) {
      return false;
    }
    return _channel.invokeMethod("isIgnoreBatteryOptimizations");
  }

  ///Android 请求 加入白名单/成为忽略电量优化的应用
  ///返回值：null代表Android sdk版本低于23，false/true 页面开启是否失败
  static requestIgnoreBatteryOptimizations(){
    if (!Platform.isAndroid) {
      return false;
    }
    return _channel.invokeMethod("requestIgnoreBatteryOptimizations");
  }

  ///Android 去设置开启 自动启动管理
  ///返回值：null代表手机不是对应平台，开启了应用详情页面， false/true 是否打开了系统对应的启动管理页面
  static toBootManagerActivity({bool noWayToSetting = true}){
    if (!Platform.isAndroid) {
      return false;
    }
    return _channel.invokeMethod("toBootManagerActivity",{"noWayToSetting":noWayToSetting});
  }

  ///Android 是否有 获取应用列表权限
  static Future<bool> hasPackagesPermission()async{
    if (!Platform.isAndroid) {
      return true;
    }
    return await _channel.invokeMethod("hasPackagesPermission");
  }

  ///Android 请求 获取应用列表权限
  static Future<bool> requestPackagesPermission() async {
    if (!Platform.isAndroid) {
      return true;
    }
    return await _channel.invokeMethod("requestPackagesPermission");
  }

}
